<template>
  <div class="app-container">
    <el-row>
      <el-col :span="24" :xs="24">
        <el-form
          :model="queryParams"
          inline
          class="search-form"
          v-show="showSearch"
        >
          <el-form-item label="入学年份">
            <el-select
              v-model="queryParams.yearNum"
              placeholder="请选择入学年份"
              clearable
              filterable
              :loading="yearLoading"
            >
              <el-option label="全部" value="" />
              <el-option
                v-for="year in yearOptions"
                :key="year.value"
                :label="year.label"
                :value="year.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="用户名">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入用户名"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleSearch">
              搜索
            </el-button>
            <el-button icon="Refresh" @click="handleReset"> 重置 </el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd">
              新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Refresh"
              @click="handleGetList"
            >
              刷新
            </el-button>
          </el-col>
          <el-col
            :span="1.5"
            v-if="!['guest', 'student'].includes(userStore.roles?.[0])"
          >
            <el-button
              type="primary"
              plain
              icon="Download"
              @click="handleExportStatistics"
              :loading="exportStatisticsLoading"
            >
              报名信息统计表导出
            </el-button>
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="handleGetList"
            :columns="columns"
          ></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="list">
          <el-table-column
            label="序号"
            align="center"
            type="index"
            width="60"
          />
          <el-table-column
            label="姓名"
            align="center"
            prop="userName"
            :show-overflow-tooltip="true"
            width="120"
            key="userName"
            v-if="columns[0].visible"
          />
          <el-table-column
            label="现任职单位"
            align="center"
            prop="trainDeptName"
            :show-overflow-tooltip="true"
            width="150"
            key="trainDeptName"
            v-if="columns[1].visible"
          >
            <template #default="scope">
              {{
                scope.row.trainDeptName ||
                getTrainDeptName(scope.row.trainDeptId) ||
                "-"
              }}
            </template>
          </el-table-column>
          <el-table-column
            label="现任职部门"
            align="center"
            prop="practiceDeptName"
            :show-overflow-tooltip="true"
            width="150"
            key="practiceDeptName"
            v-if="columns[2].visible"
          >
            <template #default="scope">
              {{
                scope.row.practiceDeptName ||
                getPracticeDeptName(scope.row.practiceDeptId) ||
                "-"
              }}
            </template>
          </el-table-column>
          <el-table-column
            label="现任职务"
            align="center"
            prop="position"
            :show-overflow-tooltip="true"
            width="150"
            key="position"
            v-if="columns[3].visible"
          />
          <el-table-column
            label="手机号码"
            align="center"
            prop="phonenumber"
            :show-overflow-tooltip="true"
            width="180"
            key="phonenumber"
            v-if="columns[4].visible"
          />
          <el-table-column
            label="申报专业领域"
            align="center"
            prop="trainMajor"
            :show-overflow-tooltip="true"
            key="trainMajor"
            v-if="columns[5].visible"
          >
            <template #default="scope">
              {{ getSpecialtyText(scope.row.trainMajor) }}
            </template>
          </el-table-column>
          <el-table-column
            label="申报高校"
            align="center"
            prop="trainUniversity"
            :show-overflow-tooltip="true"
            key="trainUniversity"
            v-if="columns[6].visible"
          >
            <template #default="scope">
              {{ getUniversityText(scope.row.trainUniversity) }}
            </template>
          </el-table-column>
          <el-table-column
            label="申报培养单位"
            align="center"
            prop="trainUnitName"
            :show-overflow-tooltip="true"
            width="180"
            key="trainUnitName"
            v-if="columns[7].visible"
          >
            <template #default="scope">
              {{ getTrainUnitName(scope.row) }}
            </template>
          </el-table-column>
          <el-table-column
            label="审核状态"
            align="center"
            prop="approvalStatus"
            :show-overflow-tooltip="true"
            width="110"
            key="approvalStatus"
            v-if="columns[8].visible"
          >
            <template #default="scope">
              <el-tag :type="getApprovalStatusType(scope.row.approvalStatus)">
                {{ getApprovalStatusText(scope.row.approvalStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="280"
            fixed="right"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-tooltip content="查看" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="View"
                  @click="handleView(scope.row)"
                >
                </el-button>
              </el-tooltip>
              <el-tooltip
                :content="canEdit(scope.row) ? '编辑' : '已提交，不允许修改'"
                placement="top"
              >
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  v-hasRole="['student']"
                  :disabled="!canEdit(scope.row)"
                  @click="handleEdit(scope.row)"
                >
                </el-button>
              </el-tooltip>
              <el-tooltip
                content="提交"
                placement="top"
                v-if="
                  scope.row.approvalStatus === 'no_submit' ||
                  scope.row.approvalStatus === 'rejected'
                "
              >
                <el-button
                  link
                  type="warning"
                  icon="Upload"
                  @click="handleSubmit(scope.row)"
                  v-hasRole="['student']"
                >
                </el-button>
              </el-tooltip>
              <el-tooltip
                content="审批"
                placement="top"
                v-if="scope.row.approvalAuth"
              >
                <el-button
                  link
                  type="success"
                  icon="Check"
                  @click="handleApprove(scope.row)"
                  v-hasRole="['enterprise_group_admin']"
                >
                </el-button>
              </el-tooltip>
              <el-tooltip content="任免表导出" placement="top">
                <el-button
                  link
                  type="info"
                  icon="Download"
                  @click="handleExportWord(scope.row)"
                  :loading="
                    exportLoadingMap[
                      scope.row.enrollId || scope.row.id || scope.row.userId
                    ] === 'word'
                  "
                  v-hasRole="['enterprise_group_admin']"
                >
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleGetList"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="SignList">
import { ElMessage } from "element-plus";
import { getCurrentInstance } from "vue";
import { useRouter } from "vue-router";
import { getList } from "@/api/sign-list";
import { getList as getSignTimeList } from "@/api/sign-time";
import { useDict } from "@/utils/dict";
import { downloadFileByApi } from "@/utils/fileDownload";
import { getTrainDeptDropdown } from "@/api/common";
import { getPracticeDeptList } from "@/api/system/dept";
import { submitApproval, handleApproval } from "@/api/approval";
import useUserStore from "@/store/modules/user";

const { proxy } = getCurrentInstance();
const router = useRouter();
const userStore = useUserStore();

// 字典数据
const { university, specialty } = useDict("university", "specialty");

const list = ref([]);
const loading = ref(true);
const total = ref(0);
const yearOptions = ref([]);
const yearLoading = ref(false);
const showSearch = ref(true);
const exportLoadingMap = ref({});
const exportStatisticsLoading = ref(false);
const trainingUnitList = ref([]);
const practiceDeptMap = ref({});

// 列显隐信息
const columns = ref([
  { key: 0, label: "姓名", visible: true },
  { key: 1, label: "现任职单位", visible: true },
  { key: 2, label: "现任职部门", visible: true },
  { key: 3, label: "现任职务", visible: true },
  { key: 4, label: "手机号码", visible: true },
  { key: 5, label: "申报专业领域", visible: true },
  { key: 6, label: "申报高校", visible: true },
  { key: 7, label: "申报培养单位", visible: true },
  { key: 8, label: "审核状态", visible: true },
]);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  yearNum: "",
  userName: "",
});

// 查询待办列表
function handleGetList() {
  loading.value = true;
  getList(queryParams)
    .then(async (res) => {
      loading.value = false;
      list.value = res.rows || [];
      total.value = res.total || 0;
      // 加载实践部门列表
      await loadAllPracticeDeptLists();
    })
    .catch(() => {
      loading.value = false;
    });
}

const handleSearch = () => {
  queryParams.pageNum = 1;
  handleGetList();
};

const handleReset = () => {
  queryParams.yearNum = "";
  queryParams.userName = "";
  handleSearch();
};

const fetchYearOptions = async () => {
  yearLoading.value = true;
  try {
    const res = await getSignTimeList({
      pageNum: 1,
      pageSize: 1000,
    });
    // 将返回的数据转换为下拉选项格式
    yearOptions.value = (res.rows || []).map((item) => ({
      label: item.yearNum,
      value: item.yearNum,
    }));
  } catch (error) {
    console.error("获取入学年份下拉数据失败:", error);
    ElMessage.error("获取入学年份数据失败，请稍后重试");
  } finally {
    yearLoading.value = false;
  }
};

// 高校名称文本显示函数
const getUniversityText = (universityValue) => {
  if (!universityValue) return "";
  const dict = university.value?.find((item) => item.value === universityValue);
  return dict ? dict.label : universityValue;
};

// 专业领域文本显示函数
const getSpecialtyText = (specialtyValue) => {
  if (!specialtyValue) return "";
  const dict = specialty.value?.find((item) => item.value === specialtyValue);
  return dict ? dict.label : specialtyValue;
};

// 获取培养单位名称
const getTrainDeptName = (trainDeptId) => {
  if (!trainDeptId) return "";
  const dept = trainingUnitList.value.find(
    (item) => item.deptId === trainDeptId
  );
  return dept ? dept.deptName : "";
};

// 获取实践部门名称
const getPracticeDeptName = (practiceDeptId) => {
  if (!practiceDeptId) return "";
  // 从所有实践部门映射中查找
  for (const deptList of Object.values(practiceDeptMap.value)) {
    const dept = deptList.find((item) => item.deptId === practiceDeptId);
    if (dept) return dept.deptName;
  }
  return "";
};

// 获取申报培养单位名称（可能包含多个，用逗号分隔）
const getTrainUnitName = (row) => {
  const unitNames = [];
  if (row.trainUnit1Name) {
    unitNames.push(row.trainUnit1Name);
  } else if (row.trainUnit1Id) {
    const unit = trainingUnitList.value.find(
      (item) => item.deptId === row.trainUnit1Id
    );
    if (unit) unitNames.push(unit.deptName);
  }
  if (row.trainUnit2Name) {
    unitNames.push(row.trainUnit2Name);
  } else if (row.trainUnit2Id) {
    const unit = trainingUnitList.value.find(
      (item) => item.deptId === row.trainUnit2Id
    );
    if (unit) unitNames.push(unit.deptName);
  }
  if (row.trainUnit3Name) {
    unitNames.push(row.trainUnit3Name);
  } else if (row.trainUnit3Id) {
    const unit = trainingUnitList.value.find(
      (item) => item.deptId === row.trainUnit3Id
    );
    if (unit) unitNames.push(unit.deptName);
  }
  return unitNames.length > 0 ? unitNames.join("、") : "-";
};

// 审核状态文本显示函数
const getApprovalStatusText = (status) => {
  const statusMap = {
    no_submit: "待提交",
    in_progress: "审核中",
    approved: "审核通过",
    rejected: "驳回",
  };
  return statusMap[status] || "待提交";
};

// 审核状态标签类型函数
const getApprovalStatusType = (status) => {
  const typeMap = {
    no_submit: "info",
    in_progress: "warning",
    approved: "success",
    rejected: "danger",
  };
  return typeMap[status] || "info";
};

// 加载培养单位列表
const loadTrainingUnitList = async () => {
  try {
    const res = await getTrainDeptDropdown({});
    trainingUnitList.value = res.data || [];
  } catch (error) {
    console.error("获取培养单位列表失败:", error);
  }
};

// 加载实践部门列表（根据培养单位ID）
const loadPracticeDeptList = async (trainDeptId) => {
  if (!trainDeptId || practiceDeptMap.value[trainDeptId]) return;
  try {
    const res = await getPracticeDeptList(trainDeptId);
    practiceDeptMap.value[trainDeptId] = res.data || [];
  } catch (error) {
    console.error("获取实践部门列表失败:", error);
  }
};

// 批量加载实践部门列表
const loadAllPracticeDeptLists = async () => {
  const trainDeptIds = new Set();
  list.value.forEach((row) => {
    if (row.trainDeptId) {
      trainDeptIds.add(row.trainDeptId);
    }
  });
  await Promise.all(
    Array.from(trainDeptIds).map((id) => loadPracticeDeptList(id))
  );
};

// 新增按钮操作
const handleAdd = () => {
  router.push({
    path: "/sign-list/edit/add",
    query: {
      mode: "add",
    },
  });
};

// 判断是否允许编辑
// 只有在未提交(no_submit)或已驳回(rejected)状态时才允许编辑
const canEdit = (row) => {
  const approvalStatus = row.approvalStatus || row.approvalInfo?.approvalStatus;
  // 如果没有状态字段，默认允许编辑（兼容旧数据）
  if (!approvalStatus) return true;
  // 只有在未提交或已驳回时才允许编辑
  return approvalStatus === "no_submit" || approvalStatus === "rejected";
};

// 查看按钮操作
const handleView = (row) => {
  const id = row.id || row.userId;
  router.push({
    path: `/sign-list/edit/${id}`,
    query: {
      mode: "detail",
    },
  });
};

// 编辑按钮操作
const handleEdit = (row) => {
  // 检查是否允许编辑
  if (!canEdit(row)) {
    ElMessage.warning("已提交的记录不允许修改，只有驳回后才能修改");
    return;
  }
  const id = row.id || row.userId;
  router.push({
    path: `/sign-list/edit/${id}`,
    query: {
      mode: "edit",
    },
  });
};

// 游客任免导出
const handleExportWord = async (row) => {
  const enrollId = row.enrollId || row.id || row.userId;
  const key = row.enrollId || row.id || row.userId;
  exportLoadingMap.value[key] = "word";

  try {
    await downloadFileByApi(
      "biz/mdt/enroll/export/word",
      { enrollId: enrollId },
      `游客任免_${row.userName || enrollId}_${new Date().getTime()}.docx`
    );
  } catch (error) {
    console.error("导出游客任免失败:", error);
    ElMessage.error("导出游客任免失败，请稍后重试");
  } finally {
    setTimeout(() => {
      exportLoadingMap.value[key] = null;
    }, 1000);
  }
};

// 报名信息统计表导出
const handleExportStatistics = async () => {
  exportStatisticsLoading.value = true;
  try {
    await downloadFileByApi(
      "biz/mdt/enroll/export/statistics",
      queryParams,
      `报名信息统计表_${new Date().getTime()}.xlsx`
    );
  } catch (error) {
    console.error("导出报名信息统计表失败:", error);
    ElMessage.error("导出报名信息统计表失败，请稍后重试");
  } finally {
    exportStatisticsLoading.value = false;
  }
};

// 提交审核
const handleSubmit = (row) => {
  const enrollId = row.id || row.enrollId;
  proxy.$modal
    .confirm("是否确认提交审核？")
    .then(function () {
      return submitApproval({
        businessId: enrollId,
        approvalTypeCode: "enroll_flow",
        approvalInfo: JSON.stringify(row),
      });
    })
    .then(() => {
      handleGetList();
      proxy.$modal.msgSuccess("提交成功");
    })
    .catch(() => {});
};

// 审批操作
const handleApprove = (row) => {
  const enrollId = row.id || row.enrollId;
  router.push({
    path: `/sign-list/edit/${enrollId}`,
    query: {
      mode: "approve",
    },
  });
};

// 初始化
onMounted(() => {
  fetchYearOptions();
  loadTrainingUnitList();
  handleGetList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}
</style>
